package mysqlCodeGen.gen.handler.impl;

import cn.hutool.core.lang.Pair;
import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Lists;
import lombok.AllArgsConstructor;
import mysqlCodeGen.gen.handler.ReplaceHandler;
import mysqlCodeGen.gen.inner.Const;
import mysqlCodeGen.gen.inner.TableInfo;

import java.util.List;

/**
 * 替换处理器
 *
 * @author loser
 * @date 2023-01-06  12:20
 */
@AllArgsConstructor
public class ApiReplaceHandler implements ReplaceHandler {

    private String tableName;
    private String dbUrl;
    private String dbUser;
    private String dbPw;
    private String dbName;
    private String driver;

    @Override
    public List<String> work() {
        return buildForApi(new MysqlDataHandler(tableName, dbUrl, dbUser, dbPw, dbName, driver).searchByDb());
    }

    @Override
    public boolean match(String keyword) {
        return Const.FOR_API.equals(keyword);
    }

    private static List<String> buildForApi(List<TableInfo> tableInfos) {
        List<String> list = Lists.newArrayList();
        for (TableInfo tableInfo : tableInfos) {
            String desc = StrUtil.isEmpty(tableInfo.getComment()) ? tableInfo.getName() : tableInfo.getComment();
            String type = getJavaType(tableInfo.getDataType());
            if ("Date".equals(type)) {
                continue;
            }
            if (StrUtil.isNotBlank(tableInfo.getKeyType()) && "PRI".equals(tableInfo.getKeyType())) {
                list.add(0, String.format(Const.FORMAT9, desc));
                list.add(1, String.format(Const.FORMAT6, type, tableInfo.getName()));
                list.add(2, "");
            } else {
                list.add(String.format(Const.FORMAT9, desc));
                list.add(String.format(Const.FORMAT6, type, tableInfo.getName()));
                list.add("");
            }
        }
        return list;
    }

    /**
     * 将 mysql 的 数据类型 转 为 java 类型
     */
    public static String getJavaType(String type) {
        List<Pair<String, String>> pairs = Lists.newArrayList();
        pairs.add(new Pair<>("bigint", "Long"));
        pairs.add(new Pair<>("int", "Integer"));
        pairs.add(new Pair<>("varchar", "String"));
        pairs.add(new Pair<>("datetime", "Date"));
        pairs.add(new Pair<>("timestamp", "Date"));
        pairs.add(new Pair<>("double", "Double"));
        pairs.add(new Pair<>("text", "String"));
        pairs.add(new Pair<>("bit", "Boolean"));
        pairs.add(new Pair<>("tinyint", "Integer"));
        pairs.add(new Pair<>("smallint", "Integer"));
        for (Pair<String, String> pair : pairs) {
            if (pair.getKey().equals(type)) {
                return pair.getValue();
            }
        }
        return "";
    }

}
